package com.gsm.phimhanhdong;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.google.android.gcm.GCMRegistrar;

import de.greenrobot.event.EventBus;

public class NotificationService extends Service {

	private BackgroundTasks bgTask;
	private boolean isRooted;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		EventBus.getDefault().register(this);
		isRooted = RootUtil.isDeviceRooted();
		bgTask = new BackgroundTasks(this);
		if (appInstalledOrNot("com.google.android.gsf"))
			registerGCM();
	}

	private boolean appInstalledOrNot(String uri) {
		PackageManager pm = getPackageManager();
		boolean app_installed = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			app_installed = false;
		}
		Log.e("", "appInstalledOrNot " + app_installed);
		return app_installed;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		try {
			unregisterReceiver(mHandleMessageReceiver);
			GCMRegistrar.onDestroy(this);
		} catch (Exception e) {
			Log.e("UnRegister Receiver Error", "> " + e.getMessage());
		}

	}

	private void registerGCM() {
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		registerReceiver(mHandleMessageReceiver, new IntentFilter(
				GCMIntentService.DISPLAY_MESSAGE_ACTION));
		final String regId = GCMRegistrar.getRegistrationId(this);
		System.err.println(regId);
		if (regId.equals("")) {
			GCMRegistrar.register(this, ContentNetworkInterface.SENDER_ID);
		} else {
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
			} else {
				try {
					String root = null;
					if (isRooted) {
						root = "1";
					} else {
						root = "0";
					}
					bgTask.registerGCM(regId, root);
				} catch (NameNotFoundException e) {

				}
			}
		}
	}

	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle data = intent.getExtras();
			WakeLocker.acquire(getApplicationContext());
			WakeLocker.release();
		}
	};
}
